package com.ruoyi.tools.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.*;
import com.alibaba.excel.enums.poi.HorizontalAlignmentEnum;
import com.alibaba.excel.enums.poi.VerticalAlignmentEnum;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.poi.util.IOUtils;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.regex.Pattern;

/**
 * 年报解析 操作处理
 *
 * @author ruoyi
 */
@RequestMapping("/analysis")
@RestController
@Slf4j
public class AnalysisController extends BaseController {

    /**
     * 查询代码生成列表
     */
    @RequiresPermissions("tools:analysis:list")
    @GetMapping("/list")
    public TableDataInfo analysisList() {
        log.info("===analysisList===调用成功");
        return null;
    }

    @Log(title = "年报解析", businessType = BusinessType.IMPORT)
    @RequiresPermissions("tools:analysis:import")
    @PostMapping("/importData")
    public void importData(@RequestParam("files") MultipartFile[] files,
                                 HttpServletResponse response) throws Exception {
        log.info("===开始调用年报解析===");
        // 准备数据存储
        List<StockContractAsset> data = new ArrayList<>();
        StockContractAsset asset = new StockContractAsset();
        asset.setId(1);
        asset.setStockName("德赛西威");
        data.add(asset);

        Map<String, String> tempMap = new HashMap<>();
        ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
        List<Future<?>> futures = new ArrayList<>();

        // 处理每个PDF文件
        for (MultipartFile file : files) {
            String x = file.getOriginalFilename();
            futures.add(executor.submit(() -> {
                try (PDDocument document = Loader.loadPDF(file.getBytes())) {
                    int totalPages = document.getNumberOfPages();
                    boolean foundSection = false;

                    int titlePage = -1; // 记录标题所在页码
                    boolean ifSection = false;
                    for (int i = 0; i < totalPages; i++) {
                        String pageText = new PDFTextStripper().getText(document);
                        String[] lines = pageText.split("\n");

                        for (String line : lines) {
                            // 定位“合并资产负债表”标题
                            if (line.contains("合并资产负债表")) {
                                titlePage = i; // 记录标题位置
                                continue;
                            }

                            // 在标题下方解析“合同负债”行
                            if (titlePage != -1 && (i == titlePage || i == titlePage + 1)
                                    && (line.contains("货币资金") || ifSection == true)) {
                                foundSection = true;
                                String[] parts = line.trim().split("\\s+"); // 按空格分割
                                // 假设数值格式为：货币资金 [数值1] [数值2]
                                if (ifSection == true && Pattern.compile("[\\u4e00-\\u9fa5]").matcher(line).find()) {
                                    System.out.println(x + "货币资金数值为空");
                                    tempMap.put(x, "--");
                                    break;
                                }
                                if (ifSection == true) {
                                    if (parts.length == 2) {
                                        System.out.println(x + "货币资金数值: " + parts[0] + ", " + parts[1]);
                                        tempMap.put(x, parts[0]);
                                        break;
                                    }
                                }
                                if (parts.length == 1) {
                                    ifSection = true;
                                    foundSection = false;
                                    continue;
                                }
                                if (parts.length == 2) {
                                    System.out.println(x + "货币资金数值: " + parts[1]);
                                    tempMap.put(x, parts[1]);
                                    break;
                                }
                                if (parts.length >= 3) {
                                    System.out.println(x + "货币资金数值: " + parts[1] + ", " + parts[2]);
                                    tempMap.put(x, parts[1]);
                                    break;
                                }
                            }
                        }
                        if (foundSection) break; // 找到后退出循环
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }));
        }

        // 等待所有任务完成
        for (Future<?> future : futures) {
            future.get();
        }
        executor.shutdown();

        // 填充数据并生成Excel
        asset.setAsset2020(tempMap.get("德赛西威：2020年年度报告.pdf"));
        asset.setAsset2021(tempMap.get("德赛西威：2021年年度报告.pdf"));
        asset.setAsset2022(tempMap.get("德赛西威：2022年年度报告.pdf"));
        asset.setAsset2023(tempMap.get("德赛西威：2023年年度报告.pdf"));
        asset.setAsset2024(tempMap.get("德赛西威：2024年年度报告.pdf"));

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        EasyExcel.write(outputStream, StockContractAsset.class)
                .sheet("货币资金")
                .doWrite(data);

        // 返回Excel文件给前端
        // 设置响应头
        String fileName = URLEncoder.encode("股票货币资金.xlsx", "UTF-8").replace("+", "%20");
        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + fileName);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        //response.setHeader("Content-Disposition", "attachment; filename=" + "dsxw.xlsx");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");

        // 直接写入Excel流到响应
        EasyExcel.write(response.getOutputStream(), StockContractAsset.class)
                .sheet("货币资金")
                .doWrite(data);
    }

    @Data
    @HeadStyle(horizontalAlignment = HorizontalAlignmentEnum.CENTER,
            verticalAlignment = VerticalAlignmentEnum.CENTER
            //,
            //fontStyle = @WriteFont(fontName = "宋体", bold = true)
    )
    @ContentStyle(horizontalAlignment = HorizontalAlignmentEnum.CENTER,
            verticalAlignment = VerticalAlignmentEnum.CENTER)
    @HeadFontStyle(fontName = "宋体", fontHeightInPoints = 11)
    @ContentFontStyle(fontName = "宋体", fontHeightInPoints = 11)
    public static class StockContractAsset {
        @ExcelProperty("序号")
        @ColumnWidth(8)
        private Integer id;

        @ExcelProperty("股票名称")
        @ColumnWidth(15)
        private String stockName;

        @ExcelProperty("2020-12-31货币资金(元)")
        @ColumnWidth(20)
        private String asset2020;

        @ExcelProperty("2021-12-31货币资金(元)")
        @ColumnWidth(20)
        private String asset2021;

        @ExcelProperty("2022-12-31货币资金(元)")
        @ColumnWidth(20)
        private String asset2022;

        @ExcelProperty("2023-12-31货币资金(元)")
        @ColumnWidth(20)
        private String asset2023;

        @ExcelProperty("2024-12-31货币资金(元)")
        @ColumnWidth(20)
        private String asset2024;

        StockContractAsset() {
        }

        public StockContractAsset(Integer id, String stockName, String asset2020,
                                  String asset2021, String asset2022,
                                  String asset2023, String asset2024) {
            this.id = id;
            this.stockName = stockName;
            this.asset2020 = asset2020;
            this.asset2021 = asset2021;
            this.asset2022 = asset2022;
            this.asset2023 = asset2023;
            this.asset2024 = asset2024;
        }
    }
}
